<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <TreeSelect
          :treeData="treeData"
          @nodeClick="nodeClick"
          title="组织结构"
        ></TreeSelect>
      </el-col>
      <el-col :span="20">
        <SearchForm
          v-show="showSearch"
          v-model="queryParams"
          :options="options.formOps"
          @onQuery="getList"
        ></SearchForm>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >新增</el-button
            >
          </el-col>

          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <Table
          ref="table"
          :auto-featch="true"
          :fetch-data="fetchData"
          :options="options.table"
        >
          <template #beforewhetherDanger>
            <el-table-column
              label="公司"
              prop="deptParentName"
              align="center"
              width="200"
              key="deptParentName"
            >
            </el-table-column>
            <el-table-column
              label="部门"
              prop="deptName"
              align="center"
              width="200"
              key="deptName"
            >
            </el-table-column>
            <el-table-column
              label="处置方案名称"
              prop="planName"
              width="250"
              align="center"
              key="planName"
            >
            </el-table-column>
            <el-table-column
              label="监控点名称"
              width="250"
              prop="monitorPointName"
              align="center"
              key="monitorPointName"
            >
            </el-table-column>
          </template>
          <template #actionButton="{ row }">
            <el-button type="text" icon="Edit" @click="handleEdit(row)"
              >修改</el-button
            >

            <el-button
              type="text"
              icon="Delete"
              style="color: red"
              @click="handleDel(row)"
              >删除</el-button
            >
          </template></Table
        >
        <DialogVform
          :formJson="formJson"
          ref="dialogVform"
          :slots="state.vFormSlots"
          @onSubmit="onSubmit"
          :title="dialogType == 'add' ? '新增危险源单元' : '修改危险源单元'"
        >
          <template v-if="dialogType == 'add'" #gsSlot>
            <el-form-item label="公司" prop="deptParentId">
              <el-select
                style="width: 100%"
                v-model="form.deptParentId"
                @change="gsChange"
                clearable
              >
                <el-option
                  v-for="dict in selectOptions"
                  :key="dict.id"
                  :label="dict.label"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </template>
          <template #bmSlot>
            <el-form-item label="部门" prop="deptId">
              <el-select
                @change="bmChange"
                :disabled="!form.deptParentId"
                v-model="form.deptId"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in selectDeptOptions"
                  :key="dict.id"
                  :label="dict.label"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </template>
          <template #faSlot>
            <el-form-item label="处置方案名称">
              <el-input
                v-model="form.planName"
                readonly
                @click="onInnerOpen('fa')"
              ></el-input>
            </el-form-item>
          </template>
          <template #jkSlot>
            <el-form-item label="监控点位名称">
              <el-input
                v-model="form.monitorPointName"
                readonly
                @click="onInnerOpen('jk')"
              ></el-input>
            </el-form-item>
          </template>
          <template #default>
            <TableSelect
              ref="faTableSelect"
              :queryApi="state.faTableSelectApi"
              :options="state.faTableSelectOps"
              :rowKey="'id'"
              rowLabel="planName"
              @onConfirm="onFaConfirm"
              rowLabelText="应急预案名称"
            ></TableSelect>
            <TableSelect
              ref="jkTableSelect"
              :queryApi="state.jkTableSelectApi"
              :options="state.jkTableSelectOps"
              :rowKey="'id'"
              rowLabel="monitorName"
              @onConfirm="onJkConfirm"
              rowLabelText="监控点位名称"
            ></TableSelect>
          </template>
        </DialogVform>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/index";
import TreeSelect from "@/components/SideTree";
import TableSelect from "@/components/tableSelect";
import formJson from "./components/options.json";
import { apis as APIS } from "@/api/hdwarning/dywh/index.js";
import { apis as YJYA } from "@/api/yjzhgl/yjyawh.js";
import { apis as SPJK } from "@/api/hdwarning/spjkxx/index.js";
import { useAsyncData, useFormJson } from "@/views/hooks/useAsyncData.js";

import { deptTreeSelect } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const state = reactive({
  jkTableSelectOps: [{ prop: "monitorName", label: "监控点位名称" }],
  faTableSelectOps: [{ prop: "planName", label: "应急预案名称" }],
  vFormSlots: ["gsSlot", "bmSlot", "faSlot", "jkSlot"],
  faTableSelectApi: YJYA.query,
  jkTableSelectApi: SPJK.query,
});

const ops = useFormJson(formJson, {
  sort: [],
  sortable: [],
});
const options = reactive({
  table: ops,
  formOps: ops.filter((i) =>
    ["dangerNodeName", "dangerLevel"].includes(i.prop)
  ),
});
const showSearch = ref(true);
const selectOptions = ref([]);
const selectDeptOptions = ref([]);
const dialogVform = ref();
const faTableSelect = ref();
const jkTableSelect = ref();
const treeData = ref([]);
const table = ref();
const editRow = ref({});
const gsChange = (val) => {
  form.value.deptParentId = val;
};
const bmChange = (val) => {
  form.value.deptId = val;
};

const onInnerOpen = (type) => {
  const { planId, planName, monitorPointId, monitorPointName } = form.value;
  if (type == "fa") {
    const values = (planId && planId.split(",")) || [];
    const names = (planName && planName.split(",")) || [];
    faTableSelect.value.open(
      values.map((item, index) => ({
        value: values[index],
        label: names[index],
      }))
    );
  } else {
    const values = (monitorPointId && monitorPointId.split(",")) || [];
    const names = (monitorPointName && monitorPointName.split(",")) || [];
    jkTableSelect.value.open(
      values.map((item, index) => ({
        value: values[index],
        label: names[index],
      }))
    );
  }
};
const onFaConfirm = (data) => {
  const values = data.map((item) => item.value);
  const names = data.map((item) => item.label);
  form.value.planId = values.join(",");
  form.value.planName = names.join(",");
};
const onJkConfirm = (data) => {
  const values = data.map((item) => item.value);
  const names = data.map((item) => item.label);
  form.value.monitorPointId = values.join(",");
  form.value.monitorPointName = names.join(",");
};
const plugEdit = (row) => {
  console.log(row);
  editRow.value = { ...row };
  form.value.planId = row.planId || "";
  form.value.planName = row.planName || "";
  form.value.monitorPointId = row.monitorPointId || "";
  form.value.monitorPointName = row.monitorPointName || "";
};
const plugAdd = () => {
  form.value = {};
};
function nodeClick(data) {
  queryParams.value.deptId = data.key;
  getList();
}

const {
  onSubmit,
  fetchData,
  dialogType,
  handleAdd,
  handleEdit,
  getList,
  handleDel,
  queryParams,
  form,
} = useAsyncData({
  APIS,
  formJson,
  dialogVform,
  table,
  proxy,
  plugEdit,
  plugAdd,
});
watch(
  () => form.value.deptParentId,
  (val) => {
    if (val) {
      const gs = selectOptions.value.find((item) => item.id == val);
      selectDeptOptions.value = gs.children;
      form.value.deptParentName = gs.label;
    } else {
      selectDeptOptions.value = [];
      form.value.deptParentName = "";
    }
  }
);
watch(
  () => form.value.deptId,
  (val) => {
    if (val) {
      console.log(form.value);
      const bm = selectDeptOptions.value.find((item) => item.id == val);
      form.value.deptName = bm.label;
    } else {
      form.value.deptName = "";
    }
  }
);
onMounted(() => {
  deptTreeSelect().then((response) => {
    selectOptions.value = response.data;
    console.log(selectOptions);
    treeData.value = response.data;
  });
});
</script>

<style lang="scss" scoped>
::v-deep.el-form-item__label {
  text-align: right !important;
}
</style>
